package com.imooc.springcloud;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

/**
 * @describte:TODO
 * @program:spring-cloud-demo
 * @author:zhengdp
 * @create:2021-10-06 21:20:49
 **/
@RestController
@Slf4j
public class Controller {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private JwtService jwtService;

    @PostMapping("/login")
    public AuthResponse login(@RequestParam String username,
                              @RequestParam String password){
        Account account = Account.builder()
                            .username(username)
                            .build();

        //TODO 验证 username + password
        String token = jwtService.token(account);
        account.setToken(token);
        account.setRefershToken(UUID.randomUUID().toString());

        // refreshtoken 跟 token 建立关联关系，用于之后的刷新
        redisTemplate.opsForValue().set(account.getRefershToken(),account);

        return AuthResponse.builder()
                .code(ErrorCode.SUCCESS)
                .account(account).build();
    }

    @PostMapping("/refresh")
    public AuthResponse refresh(@RequestParam String refreshToken){
        Account account = (Account) redisTemplate.opsForValue().get(refreshToken);
        if(account == null){
            return AuthResponse.builder().code(ErrorCode.USER_NOT_FOUND)
                    .build();
        }
        String jwt = jwtService.token(account);
        account.setToken(jwt);
        account.setRefershToken(UUID.randomUUID().toString());
        redisTemplate.delete(refreshToken);
        redisTemplate.opsForValue().set(account.getRefershToken(),account);
        return AuthResponse.builder()
                .code(ErrorCode.SUCCESS)
                .account(account).build();

    }

    @GetMapping("/verify")
    public AuthResponse verify(@RequestParam String token,
                               @RequestParam String username){
        boolean success = jwtService.verify(token,username);

        return AuthResponse.builder()
                // todo 此处最后用Invalid token之类的错误信息
                .code(success ? ErrorCode.SUCCESS : ErrorCode.USER_NOT_FOUND)
                .build();
    }
}
